/**
 * bug 9.4 16:49 之前的 swaggerMode 1.显示 2.非字典
 * @type {string}
 */

let object = `
id (integer, optional): id$$编号$false$false$false$$1$ ,
ip (string, optional): ip$$IP$true$true$false$$9$ ,
message (string, optional): message$$信息$false$false$false$$11$ ,
modulename (string, optional): modulename$$模块$true$true$false$$5$ ,
operatetime (string, optional): operatetime$$操作时间$true$true$false$$10$ ,
orgid (integer, optional): orgid$$机构编号$false$false$false$$4$ ,
remark (string, optional): remark$$控制层地址$false$false$false$$12$ ,
rentid (integer, optional): rentid$$客户编号$false$false$false$$3$ ,
show_orgid (string, optional): show_orgid$$机构名称$true$true$false$$14$ ,
show_rentid (string, optional): show_rentid$$客户名称$true$true$false$$13$ ,
show_status (string, optional): show_status$$状态名称$true$true$false$$16$ ,
status (integer, optional): status$$操作状态$false$false$false$$17$ ,
target (string, optional): target$$操作对象$false$false$false$$8$ ,
type (string, optional): type$$操作类型$true$true$false$$6$ ,
useraccount (string, optional): useraccount$$用户账号$true$true$false$$2$
`;
/**
 *  'table'
 *  'form'
 *
 * @type {string}
 */
let model = 'table'; // 解析模式
let config = {
  table: 'table', // table 名称
  form: 'formDialog', // form 名称
  store: 'HUOZHU', // 前端库
  advanced: true, // 高级解析模式
  selectModel: false, // makeCode 查看模式
  dictionaries: {}, // 字典集合
  dictionariesSearch: [], // 搜索字典集合
}; // 配置文件
const formConfig = {
  cols: 2, // form 中 每行多少列
};
const typeMap = {
  string: '',
  integer: 0,
};

// console.log('-------------------------------------------------------------');
// console.log(1);
let a = object.split('\n');
// console.log(a);
// console.log('-------------------------------------------------------------');
let b = [];
let item = '';
for (item of a) {
  if (item === '') continue;
  item = item.trim();
  if (item.lastIndexOf(',') + 1 === item.length) {
    item = item.substring(0, item.length - 1);
  }
  item = item.trim();
  b.push(item);
}
// console.log(2);
// console.log(b);
// console.log('-------------------------------------------------------------');

let c = [];
let i = 0;
for (item of b) {
  c[i] = item.split(':');
  if(c[i].length >= 2){
    c[i][0] = c[i][0].trim();
    c[i][1] = c[i][1].trim();
    i++;
  }
}

// console.log(3);
// console.log(c);
// console.log('-------------------------------------------------------------');
if (model === 'table' || model === 'all') {
  let d = {};
  let string = '';
  for (i = 0; i < c.length; i++) {
    if(c[i].length < 2) continue;
    // let step = {};
    let cSplit = c[i][0].split('(');
    // step[cSplit[0].trim()] = cSplit[1].split(',')[0].trim();
    let cType = cSplit[1].split(',')[0].trim();
    let cName = cSplit[0].trim();
    if(!config.advanced){
      d[c[i][1]] = cSplit[0].trim();
    } else {
      let advanced = c[i][1].trim().split('$');
      let show = advanced[3] === 'true'; // 是否显示
      if(!show) continue;
      let cNotes = advanced[0]; // label
      let cRemarks = advanced[2]; // 备注
      let search = advanced[4] === 'true'; // 是否搜索
      let cDictionariesName = !!advanced[6]; // 是否字典
      let index = advanced[7]; // 字段索引
      if(search) {
        let item = `autoVue_${config.table}_` + cName;
        config.dictionariesSearch.push(item);
        string += `<el-form-item label="${cNotes}" prop="${cName}">
  <el-input type="text"
            class="input"
            v-model="${item}"
            placeholder="${cNotes}" spellcheck="false" auto-capitalize="off" auto-complete="off"
            auto-correct="off"></el-input>
</el-form-item>
`;
      }
      d[cName] = {
        label: cNotes,
        prop: cDictionariesName ? ('show_' + cName) : cName,
        minWidth: '0px',
        cRemarks,
        search,
        index,
      };
    }
  }

  // console.log(4);
  // console.log(d);
  // console.log('-------------------------------------------------------------');
  let e = [];

  if (!config.advanced){
    for (let index in d) {
      if (d.hasOwnProperty(index)) {
        e.push({
          label: index.split('$')[0],
          prop: d[index],
          minWidth: '0px',
          search: false,
        });
      }
    }
    console.log(e);
  } else {
    let key = [];
    let keys = Object.keys(d);
    for(let index of keys){
      key.push(d[index]);
    }
    key = bubbleSort(key);
    let e = [];
    for(let item of key){
      delete item.index;
      e.push(item);
    }
    console.log(e);
    console.log('-------------------------------------------------------------');
    console.log(config.dictionariesSearch);
    console.log('-------------------------------------------------------------');
    console.log(string);
  }
  // console.log(5);
// console.log('-------------------------------------------------------------');
  /**
   * [
   *  { label: '客户地址', prop: 'address' },
   *  { label: '创建日期', prop: 'createtime' },
   *  { label: '客户简介', prop: 'descr' },
   *  { label: '客户ID', prop: 'id' },
   *  { label: '客户名称', prop: 'name' },
   *  { label: '客户网站', prop: 'netstation' },
   *  { label: '当前页数', prop: 'page' },
   *  { label: '客户编码', prop: 'rentcode' },
   *  { label: '分页行数', prop: 'rows' },
   *  { label: '客户的机构规模（人数）', prop: 'scale' },
   *  { label: '具体人数', prop: 'scalename' },
   *  { label: '客户所属行业名称', prop: 'trade' },
   *  { label: '客户所属行业,见字典表,可以多选，dictionary接口', prop: 'trades' },
   *  { label: '客户性质', prop: 'type' },
   *  { label: '客户性质名称', prop: 'typename' }
   * ]
   *
   *
   */
}
if (model === 'form' || model === 'all') {
  let d = {};
  let string = '';
  for (i = 0; i < c.length; i++) {
    if(c[i].length < 2) continue;
    let cSplit = c[i][0].split('(');
    let cType = cSplit[1].split(',')[0].trim();
    let cName = cSplit[0].trim();
    if(!config.advanced){
      let cNotes = c[i][1].trim();
      d[cName] = {
        value: typeMap[cSplit[1].split(',')[0].trim()],
        rule: [],
      };

      if(config.selectModel) {
        string += `
<el-form-item prop="${cName}" label="${cNotes}"><span>{{${config.form}.${cName}}}</span></el-form-item>`
      } else {
        switch (cType) {
          case 'string':
            string += `
<el-form-item prop="${cName}" label="${cNotes}">
  <el-input 
      type="text"
      v-model="${config.form}.${cName}"
      placeholder="${cNotes}"></el-input>
</el-form-item>`;
            break;
          case 'integer':
            string += `
<el-form-item prop="${cName}" label="${cNotes}">
  <el-select v-model="${config.form}.${cName}" placeholder="请选择">
    <el-option
      v-for="item in ${config.store}.${cName}"
      :key="item.dictionaryid"
      :label="item.value"
      :value="item.dictionaryid">
    </el-option>
  </el-select>
</el-form-item>`;
            break;
        }
      }
    } else {
      let advanced = c[i][1].trim().split('$');
      let cNotes = advanced[0]; // label
      let cRemarks = advanced[2]; // 备注
      let Default = parseInt(advanced[2]) || advanced[1]; // 默认值
      let show = advanced[3]; // 是否显示
      let search = advanced[4]; // 是否搜索
      let cDictionariesName = advanced[6]; // 字典名称
      let index = advanced[7]; // 字段索引
      let rule = advanced[8]?advanced[8].split(','):[]; // 规则

      if(!!cDictionariesName) {
        config.dictionaries[cName] = cDictionariesName;
        let step = [];
        rule.forEach(value => {
          step.push(value + '__change');
        });
        rule = step;
      }
      d[cName] = {
        prop: cName,
        value: Default || typeMap[cSplit[1].split(',')[0].trim()],
        rule,
        cRemarks,
        index,
        code: AutoCodeString({
          config,
          cName,
          cDictionaries:!!cDictionariesName,
          show,
          cNotes,
        }),
      };
    }
  }
  let e = {};

  if (!config.advanced){
    console.log(d);
    console.log('\n--------------------------------------------\n');
    console.log(string);
  } else {
    let key = [];
    let keys = Object.keys(d);
    for(let index of keys){
      key.push(d[index]);
    }
    key = bubbleSort(key);
    let HTMLCode = [];
    for(let index in key){
      if(config.selectModel) {
        e[key[index].prop] = key[index].value;
      } else {
        e[key[index].prop] = {
          value: key[index].value,
          rule: key[index].rule,
          cRemarks: key[index].cRemarks,
        };
      }
      HTMLCode.push(key[index].code);
    }

    console.log(e);
    console.log('\n--------------------------------------------\n');
    console.log(config.dictionaries);
    console.log('\n--------------------------------------------\n');
    let dictionary = {};
    for (let index in config.dictionaries) {
      dictionary[index] = [];
    }
    console.log(dictionary);
    console.log('\n--------------------------------------------\n');
    console.log(makeHTMLCode(HTMLCode));
  }
}


function AutoCodeString({config,cDictionaries,cName,cNotes,show}) {
  if(show === 'false') {
    console.log(`存在 隐藏！ 对应字段为:${cName}  对应label为:${cNotes}`);
    return '';
  }
  let string = '';
  if(config.selectModel){
    if(cDictionaries){
      string += `      <el-form-item prop="${cName}" label="${cNotes}"><span>{{tree.select.show_${cName}}}</span></el-form-item>`;
    } else {
      string += `      <el-form-item prop="${cName}" label="${cNotes}"><span>{{tree.select.${cName}}}</span></el-form-item>`;
    }
  }else{
    if(cDictionaries){
      string += `      <el-form-item prop="${cName}" label="${cNotes}">
        <el-select v-model="${config.form}.${cName}" placeholder="请选择">
          <el-option
            v-for="item in ${config.store}.${cName}"
            :key="item.dictionaryid"
            :label="item.value"
            :value="item.dictionaryid">
          </el-option>
        </el-select>
      </el-form-item>`;
    } else {
      string += `      <el-form-item prop="${cName}" label="${cNotes}">
        <el-input 
            type="text"
            v-model="${config.form}.${cName}"
            placeholder="${cNotes}"></el-input>
      </el-form-item>`;
    }
  }
  return string;
}

function bubbleSort(arr){
  let temp = 0;
  for (let i = 1; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i; j++) {
      if (parseInt(arr[j].index) > parseInt(arr[j + 1].index)) {
        temp = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

function makeHTMLCode(codeArray) {
  let rowStep = '';
  let colsStep = [];
  let length = codeArray.length;
  let span = 24 / formConfig.cols - 1;
  let offset = 1;
  for (let item of codeArray) {
    offset = colsStep.length === 0? 0:1;
    colsStep.push(cols(item,span,offset));
    if (colsStep.length === formConfig.cols) {
      rowStep += row(colsStep);
      colsStep = [];
    }
  }
  rowStep += row(colsStep);
  return form(rowStep);

  function form (row) {
    return `<s-form :form="${config.form}" ref="${config.form}">
${row}</s-form>
`;
  }
  function row (colsArray) {
    if (colsArray.length === 0) return '';
    let cols = '';
    for (let item of colsArray) {
      cols += item;
    }
    return `  <el-row>
${cols}  </el-row>
`;
  }
  function cols (formItem, span, offset) {
    return `    <el-col :xs="24" :lg="{span: ${span}, offset: ${offset}}">
${formItem}
    </el-col>
`
      ;
  }
}
